package com.sgx.learning.luban.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class NioServer {

    private static List<SocketChannel> channelList = new ArrayList<>();

    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocket = ServerSocketChannel.open();
        serverSocket.socket().bind(new InetSocketAddress(9000));
        serverSocket.configureBlocking(false);
        System.out.println("服务器启动成功");
        while(true) {
            SocketChannel channel = serverSocket.accept();
            if(channel != null) {
                System.out.println("连接成功");
                channel.configureBlocking(false);
                channelList.add(channel);
            }
            Iterator<SocketChannel> iterator = channelList.iterator();
            while (iterator.hasNext()) {
                SocketChannel so = iterator.next();
                ByteBuffer b = ByteBuffer.allocate(128);
                int read = so.read(b);
                if(read > 0) {
                    System.out.println("接收到客户端数据:" + new String(b.array(),0,read));
                } else if(read == -1) {
                    iterator.remove();
                    System.out.println("断开连接");
                }
            }
        }
    }
}
